<?php
/**
 * 上传类
 *
 * PHP Version 5.6
 *
 * @author    guanxu <510104561@qq.com>
 * @time      2017/08/11
 */
namespace Admin\Controller;
use Common\Common\UploadUtil;
use Think\Controller;
use Common\Common\ConstantUtil;

Class UploadController extends CommonController {


    private $CONFIG;


    public function config() {
        //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
        //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header

        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");
        /* 上传图片配置项 */
        $this->CONFIG["imageActionName"]    =  "uploadimage"; /* 执行上传图片的action名称 */
        $this->CONFIG["imageFieldName"]     = "uploadimage"; /* 提交的图片表单名称 */
        $this->CONFIG["imageMaxSize"]       = 204800000; /* 上传大小限制，单位B */
        $this->CONFIG["imageAllowFiles"]    = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; /* 上传图片格式显示 */
        $this->CONFIG["imageCompressEnable"]= true; /* 是否压缩图片,默认是true */
        $this->CONFIG["imageCompressBorder"]= 1600; /* 图片压缩最长边限制 */
        $this->CONFIG["imageInsertAlign"]   = "none"; /* 插入的图片浮动方式 */
        $this->CONFIG["imageUrlPrefix"]     = ""; /* 图片访问路径前缀 */
        $this->CONFIG["imagePathFormat"]    = "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */
    /* 涂鸦图片上传配置项 */
    $this->CONFIG["scrawlActionName"]   =  "uploadscrawl"; /* 执行上传涂鸦的action名称 */
    $this->CONFIG["scrawlFieldName"]    =  "uploadimage"; /* 提交的图片表单名称 */
    $this->CONFIG["scrawlPathFormat"]   =  "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
    $this->CONFIG["scrawlMaxSize"]      =  2048000; /* 上传大小限制，单位B */
    $this->CONFIG["scrawlUrlPrefix"]    =  ""; /* 图片访问路径前缀 */
    $this->CONFIG["scrawlInsertAlign"]  =  "none";

    /* 截图工具上传 */
    $this->CONFIG["snapscreenActionName"]   =  "uploadimage"; /* 执行上传截图的action名称 */
    $this->CONFIG["snapscreenPathFormat"]   =  "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
    $this->CONFIG["snapscreenUrlPrefix"]    =  ""; /* 图片访问路径前缀 */
    $this->CONFIG["snapscreenInsertAlign"]  =  "none"; /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    $this->CONFIG["catcherLocalDomain"] =  ["127.0.0.1", "localhost", "img.baidu.com"];
    $this->CONFIG["catcherActionName"]  =  "catchimage"; /* 执行抓取远程图片的action名称 */
    $this->CONFIG["catcherFieldName"]   =  "source"; /* 提交的图片列表表单名称 */
    $this->CONFIG["catcherPathFormat"]  =  "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
    $this->CONFIG["catcherUrlPrefix"]   =  ""; /* 图片访问路径前缀 */
    $this->CONFIG["catcherMaxSize"]     =  2048000; /* 上传大小限制，单位B */
    $this->CONFIG["catcherAllowFiles"]  =  [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; /* 抓取图片格式显示 */

    /* 上传视频配置 */
    $this->CONFIG["videoActionName"]    =  "uploadvideo"; /* 执行上传视频的action名称 */
    $this->CONFIG["videoFieldName"]     =  "uploadimage"; /* 提交的视频表单名称 */
    $this->CONFIG["videoPathFormat"]    =  "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
    $this->CONFIG["videoUrlPrefix"]     =  ""; /* 视频访问路径前缀 */
    $this->CONFIG["videoMaxSize"]       =  102400000; /* 上传大小限制，单位B，默认100MB */
    $this->CONFIG["videoAllowFiles"]    =  [
            ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"]; /* 上传视频格式显示 */

    /* 上传文件配置 */
    $this->CONFIG["fileActionName"] =  "uploadfile"; /* controller里,执行上传视频的action名称 */
    $this->CONFIG["fileFieldName"]  =  "uploadimage"; /* 提交的文件表单名称 */
    $this->CONFIG["filePathFormat"] =  "/Uploads/{yyyy}-{mm}-{dd}/{time}{rand:6}"; /* 上传保存路径,可以自定义保存路径和文件名格式 */
    $this->CONFIG["fileUrlPrefix"]  =  ""; /* 文件访问路径前缀 */
    $this->CONFIG["fileMaxSize"]    =  51200000; /* 上传大小限制，单位B，默认50MB */
    $this->CONFIG["fileAllowFiles"] =  [
            ".png", ".jpg", ".jpeg", ".gif", ".bmp",
            ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
            ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
            ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
        ]; /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    $this->CONFIG["imageManagerActionName"]     =  "listimage"; /* 执行图片管理的action名称 */
    $this->CONFIG["imageManagerListPath"]       =  "/public/images/upload/"; /* 指定要列出图片的目录 */
    $this->CONFIG["imageManagerListSize"]       =  20; /* 每次列出文件数量 */
    $this->CONFIG["imageManagerUrlPrefix"]      =  ""; /* 图片访问路径前缀 */
    $this->CONFIG["imageManagerInsertAlign"]    =  "none"; /* 插入的图片浮动方式 */
    $this->CONFIG["imageManagerAllowFiles"]     =  [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    $this->CONFIG["fileManagerActionName"]  =  "listfile"; /* 执行文件管理的action名称 */
    $this->CONFIG["fileManagerListPath"]    =  "/public/images/upload/"; /* 指定要列出文件的目录 */
    $this->CONFIG["fileManagerUrlPrefix"]   =  ""; /* 文件访问路径前缀 */
    $this->CONFIG["fileManagerListSize"]    =  20;; /* 每次列出文件数量 */
    $this->CONFIG["fileManagerAllowFiles"]  =  [
            ".png", ".jpg", ".jpeg", ".gif", ".bmp",
            ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
            ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
            ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
        ]; /* 列出的文件类型 */
        //   = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("config.json")), true);

        $param = I("get.");
        $action = $param['action'];

        switch ($action) {
            case 'config':
                $result =  json_encode($this->CONFIG);
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->action_upload($param);
                break;
            /* 列出图片 */
            case 'listimage':
                $result = $this->action_list($param);
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->action_list($param);
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->action_crawler($param);
                break;

            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }

        /* 输出结果 */
        if (isset($param["callback"])) {
            if (preg_match("/^[\w_]+$/", $param["callback"])) {
                echo htmlspecialchars($param["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }

    /**
     * @param $param
     * @return string
     * 上传
     */
    private function action_upload($param) {


        $base64 = "upload";
        switch (htmlspecialchars($param['action'])) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $this->CONFIG['imagePathFormat'],
                    "maxSize" => $this->CONFIG['imageMaxSize'],
                    "allowFiles" => $this->CONFIG['imageAllowFiles']
                );
                $fieldName = $this->CONFIG['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $this->CONFIG['scrawlPathFormat'],
                    "maxSize" => $this->CONFIG['scrawlMaxSize'],
                    "allowFiles" => $this->CONFIG['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $this->CONFIG['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $this->CONFIG['videoPathFormat'],
                    "maxSize" => $this->CONFIG['videoMaxSize'],
                    "allowFiles" => $this->CONFIG['videoAllowFiles']
                );
                $fieldName = $this->CONFIG['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $this->CONFIG['filePathFormat'],
                    "maxSize" => $this->CONFIG['fileMaxSize'],
                    "allowFiles" => $this->CONFIG['fileAllowFiles']
                );
                $fieldName = $this->CONFIG['fileFieldName'];
                break;
        }


        /* 生成上传实例对象并完成上传 */
        $up = new UploaderController($fieldName, $config, $base64);

        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */

        /* 返回数据 */
        return json_encode($up->getFileInfo());


    }
    private function action_list($param) {

        /* 判断类型 */
        switch ($param['action']) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $this->CONFIG['fileManagerAllowFiles'];
                $listSize = $this->CONFIG['fileManagerListSize'];
                $path = $this->CONFIG['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $this->CONFIG['imageManagerAllowFiles'];
                $listSize = $this->CONFIG['imageManagerListSize'];
                $path = $this->CONFIG['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($param['size']) ? htmlspecialchars($param['size']) : $listSize;
        $start = isset($param['start']) ? htmlspecialchars($param['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;
    }
    private function action_crawler($param) {


        set_time_limit(0);
        /* 上传配置 */
        $config = array(
            "pathFormat" =>  $this->CONFIG['catcherPathFormat'],
            "maxSize" =>  $this->CONFIG['catcherMaxSize'],
            "allowFiles" =>  $this->CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName =  $this->CONFIG['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        if (isset($param[$fieldName])) {
            $source = $param[$fieldName];
        } else {
            $source = $param[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new UploaderController($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }

        /* 返回抓取数据 */
        return json_encode(array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        ));

    }

    private function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = array(
                            'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime'=> filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }


    /**
     * 上传
     * @param string $type
     * @return array|bool|string
     */
    public function image($type="") {
        if(empty($type)) $type = array('jpg', 'gif', 'png', 'jpeg',"zip","rar","tar.gz");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     10485760  ;// 设置附件上传大小 3MB 3145728/3M
        $upload->exts      =     $type;// 设置附件上传类型
        $upload->rootPath  =     './'.UploadUtil::UPLOAD_PATH.'/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            return  $upload->getError();
        }else{// 上传成功
            return $info;
        }
    }



}